﻿#include <QScrollBar>
#include "Public.h"
#include "CPubAlarmTable.h"
#include "CGlobal.h"
#include "CAlarmDetailsDlg.h"
#include "CConnectDevDlg.h"
#include "CSqlOper.h"
#include "CModelMng.h"
#include "CAlarmRecordQuery.h"

CPubAlarmTable::CPubAlarmTable(int nType, QString sCardGuid, QWidget *parent)
	: m_nCardType(nType),m_sCardGuid(sCardGuid),QWidget(parent)
{
	ui.setupUi(this);
	initUI();
	initVecDevData();
	m_bConnectDevChanged = true;
	m_pTimer = new QTimer(this);
	connect(m_pTimer, SIGNAL(timeout()), this, SLOT(slotRefreshUI()));
	m_pMenu = new QMenu(this);
	m_pMoreAct = new QAction(QIcon(":/icon/More.png"), A2T("更多"));
	m_pConnectDevAct = new QAction(QIcon(":/icon/Connect.png"), A2T("绑定设备"));
	m_pMenu->addAction(m_pMoreAct);
	m_pMenu->addAction(m_pConnectDevAct);
	ui.toolButtonMore->setMenu(m_pMenu);
	ui.toolButtonMore->setPopupMode(QToolButton::InstantPopup);
	connect(m_pConnectDevAct, &QAction::triggered, this, &CPubAlarmTable::slotConnectDev);
	connect(m_pMoreAct, &QAction::triggered, this, &CPubAlarmTable::slotMore);
	connect(this, &CPubAlarmTable::sigShowImg, this, &CPubAlarmTable::slotShowImg);
}

CPubAlarmTable::~CPubAlarmTable()
{
	m_pTimer->stop();
	// 断开所有连接，防止信号队列中的调用
	disconnect(m_pTimer, nullptr, this, nullptr);
	delete m_pTimer;
	m_pTimer = nullptr;
}

void CPubAlarmTable::initUI()
{
	//禁止编辑
	ui.tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
	//单选行
	ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	//模式为单选
	ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
	//行末尾自动拉伸填充
	ui.tableView->horizontalHeader()->setStretchLastSection(true);
	//左边序号列隐藏
	ui.tableView->verticalHeader()->setVisible(false);
	m_pModel = new QStandardItemModel(this);
	QStringList headerListAction;		//水平表头
	headerListAction << A2T("序号") << A2T("摄像头名") << A2T("报警类型") <<
		A2T("报警时间") << A2T("报警等级") << A2T("是否确认") << A2T("操作");

	QList<quint16> listColumnWidth;		//列宽
	listColumnWidth << 50 << 180 << 150 << 180 << 120 << 100;

	//设置列数
	m_pModel->setColumnCount(headerListAction.count());
	//设置表头
	m_pModel->setHorizontalHeaderLabels(headerListAction);
	ui.tableView->setModel(m_pModel);
	//设置列宽
	for (int i = 0; i < listColumnWidth.count(); i++)
	{
		ui.tableView->setColumnWidth(i, listColumnWidth.at(i));
	}
}

void CPubAlarmTable::initVecDevData()
{
	if (m_nCardType == 0)
	{
		return;
	}
	else if (m_nCardType == 1)
	{
		//首先根据传进来的Guid去数据库中查询是否有这个卡片的绑定设备数据
		QString sErrMsg = "";
		QVector<QSqlRecord> vecInfo;
		CSqlOper::instance().selectPubCardCfg(m_sCardGuid, vecInfo, sErrMsg);
		if (vecInfo.size() == 0)//默认绑定全部的报警数据
		{
			for (int i = 0; i < CModelMng::instance().m_vecDev.size(); i++)
			{
				m_sDevList += CModelMng::instance().m_vecDev[i]->m_sDevGuid;
				m_sDevList += ",";
				m_vecDevData.push_back(CModelMng::instance().m_vecDev[i]->m_pDevMng->m_pDev->m_pDevData);
			}
			bool bRet = CSqlOper::instance().insertPubCardCfg(m_sCardGuid, enPubStatisticsChat, m_sDevList, sErrMsg);
		}
		else
		{
			for (int i = 0; i < vecInfo.size(); i++)
			{
				m_sDevList = vecInfo[i].value("DEV_LIST").toString();
			}
			QStringList slistDev = m_sDevList.split(",");
			for (int i = 0; i < slistDev.size(); i++)
			{
				for (int j = 0; j < CModelMng::instance().m_vecDev.size(); j++)
				{
					if (slistDev[i] == CModelMng::instance().m_vecDev[j]->m_sDevGuid)
					{
						m_vecDevData.push_back(CModelMng::instance().m_vecDev[j]->m_pDevMng->m_pDev->m_pDevData);
					}
				}
			}
		}
	}
}

void CPubAlarmTable::slotShowImg(QString sAlarmGuid)
{
	CAlarmDetailsDlg oper(sAlarmGuid);
	oper.exec();
}

void CPubAlarmTable::slotMore()
{
	CAlarmRecordQuery oper;
	oper.exec();
}

void CPubAlarmTable::slotConnectDev()
{
	CConnectDevDlg oper;
	oper.setData(m_sDevList);
	int nRet = oper.exec();
	if (nRet == QDialog::Accepted)
	{
		QString sDevList = oper.getDevList();
		//更新数据库
		QString sErrMsg = "";
		CSqlOper::instance().updatePubCardCfg(m_sCardGuid, sDevList, sErrMsg);
		//更新m_vecDevData
		m_vecDevData.clear();
		for (int i = 0; i < CModelMng::instance().m_vecDev.size(); i++)
		{
			if (sDevList.contains(CModelMng::instance().m_vecDev[i]->m_sDevGuid))
			{
				m_vecDevData.push_back(CModelMng::instance().m_vecDev[i]->m_pDevMng->m_pDev->m_pDevData);
			}
		}
		m_bConnectDevChanged = true;
		m_sDevList = sDevList;
	}
}

bool sortAlarm(AlarmItem alarm1, AlarmItem alarm2)
{
	return QDateTime::fromString(alarm1.sAlarmTime,"yyyy/MM/dd hh:mm:ss") > QDateTime::fromString(alarm2.sAlarmTime, "yyyy/MM/dd hh:mm:ss");
}

void CPubAlarmTable::slotRefreshUI()
{
	if (!isVisible())
	{
		return;
	}
	// 只保存滚动条位置，不保存选中行
	int verticalScrollValue = ui.tableView->verticalScrollBar()->value();
	int horizontalScrollValue = ui.tableView->horizontalScrollBar()->value();

	QVector<AlarmItem> vecAlarm;
	for (int i = 0; i < m_vecDevData.size(); i++)
	{
		CDevDataCam* pDevData = m_vecDevData[i];
		pDevData->m_pMutex->lock();
		vecAlarm.append(pDevData->m_vecAlarm);
		pDevData->m_pMutex->unlock();
	}
	if (vecAlarm.size() == 0 && !m_bConnectDevChanged)
	{
		return;
	}
	//根据报警时间排序处理
	qSort(vecAlarm.begin(), vecAlarm.end(), sortAlarm);//反向排序
	ui.tableView->blockSignals(true);
	m_pModel->removeRows(0, m_pModel->rowCount());
	for (int i = 0; i < vecAlarm.size(); i++)
	{
		QList<QStandardItem*> item;
		item.append(new QStandardItem(QString::number(i)));//序号
		item.append(new QStandardItem(vecAlarm[i].sCamerName));//摄像头名称
		item.append(new QStandardItem(vecAlarm[i].sAlarmType));//报警类型
		item.append(new QStandardItem(vecAlarm[i].sAlarmTime));//报警时间
		item.append(new QStandardItem(QString::number(vecAlarm[i].nAlarmLevel)));//报警等级
		if (vecAlarm[i].nIsConfirm == 1)
		{
			item.append(new QStandardItem(A2T("是")));//是否确认
		}
		else
		{
			item.append(new QStandardItem(A2T("否")));//是否确认
		}
		item.append(new QStandardItem(""));//操作
		//设置居中显示
		for (int nRow = 0; nRow < item.count(); nRow++)
		{
			item.at(nRow)->setTextAlignment(Qt::AlignCenter);
		}
		m_pModel->insertRow(m_pModel->rowCount(), item);
		// 添加按钮到操作列
		QPushButton *btn = new QPushButton(A2T("查看明细"));
		btn->setProperty("row", i);
		btn->setProperty("Guid", vecAlarm[i].sGuid);
		connect(btn, &QPushButton::clicked, this, [this]() {
			QPushButton *senderBtn = qobject_cast<QPushButton*>(sender());
			if (senderBtn) {
				QString sGuid = senderBtn->property("Guid").toString();
				emit sigShowImg(sGuid);
			}
		});
		ui.tableView->setIndexWidget(m_pModel->index(m_pModel->rowCount() - 1, 6), btn);
		if (m_pModel->rowCount() > 50)
		{
			m_pModel->removeRows(m_pModel->rowCount() - 1, 1);//移除最后一行
		}
	}
	// 恢复滚动条位置（不恢复选中行）
	ui.tableView->verticalScrollBar()->setValue(verticalScrollValue);
	ui.tableView->horizontalScrollBar()->setValue(horizontalScrollValue);

	m_bConnectDevChanged = false;
	// 解除信号阻塞
	ui.tableView->blockSignals(false);
}

void CPubAlarmTable::refreshData(bool bRefresh)
{
	if (bRefresh)
	{
		m_pTimer->start(1000);
	}
	else
	{
		m_pTimer->stop();
	}
}
